<?php

namespace fast;

use think\Db;

use think\Exception;
use fast\Http;
/**
 * Http 请求类
 */
class AdapayUtil
{

  
       
    public $appid = 'app_0577dafe-f743-4a6e-b0fa-83cb497573ee';

    public function __construct(){
        require_once dirname(__FILE__) . '/Adapay/AdapaySdk/init.php';
        \AdaPay\AdaPay::init(self::getConfig(), "live", true);
    }
// MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCI0Pz/e3rrPQcFqobHAKcqLVIMM6ED9iviwG63a/oDTC3hE+9qXdih7CxBJYI37snVvMu6saaHIn3blvfpi17gEKiPH8Rt8OoOo1i9t+hb7MIW+HFyfmDGfkxTGXzPgTfUkcw6V6X9k3L038u7dI8s8WBchtqLWEZT6Ku33kIL6QIDAQAB
    public static function getConfig(){
        $jsonPath = [
            "api_key_live" => "api_live_d58aacba-3c33-4f41-93f0-efb49563a490",
            "api_key_test" => "api_test_0d13f943-4e70-4e42-a93a-a54c6eb69057",
            "rsa_public_key" => "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwN6xgd6Ad8v2hIIsQVnbt8a3JituR8o4Tc3B5WlcFR55bz4OMqrG/356Ur3cPbc2Fe8ArNd/0gZbC9q56Eb16JTkVNA/fye4SXznWxdyBPR7+guuJZHc/VW2fKH2lfZ2P3Tt0QkKZZoawYOGSMdIvO+WqK44updyax0ikK6JlNQIDAQAB",
            "rsa_private_key" => "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIjQ/P97eus9BwWqhscApyotUgwzoQP2K+LAbrdr+gNMLeET72pd2KHsLEElgjfuydW8y7qxpocifduW9+mLXuAQqI8fxG3w6g6jWL236Fvswhb4cXJ+YMZ+TFMZfM+BN9SRzDpXpf2TcvTfy7t0jyzxYFyG2otYRlPoq7feQgvpAgMBAAECgYAKkDg4cYw4BWo5YcUuMDq34u/myUWxTJxu0XS67LdM8eDI9AUULVLAjb+M+BxpvSIQQpdoPrcgz+Tvw2Q4v+3/OXEEHcT4sEBDPjmkWPLoIaxiAvhtQtjmxXHUyweaIxW1pjicHVmVhx27PhhHPUqheiErIhEC0kgh8R376A89QQJBAN8lBicyd42ZKk3OCHj/NhImwm04DKPPdshm5M71ZTQaPjzIp6jdugIwJIHPi0Eb1bgiAppFGprcTkcXm+JcwaUCQQCc9f+fRO/Zp7wjguNBYH4O/rXq0pTXOGNsm3O2K66RHsOqtIen0NIAZoOtVsiB4EdmcOFZc81CbNgIyrKluoX1AkB2tQuA7qgK++A1Y9W+CIaLQXNNBvQycLuQAKzYLFOaVBun2lbWzp2VbGb/Z5l9GYGoYu9fgkOU/n3l8/lJgm7BAkBLy//FSeUJlpakD3DvAUnes+HlpAt8Yx6gM/GM50tFiTW0GbnosE65IsgzzNTG4yeXsKsiJ2nXyfgJRtk+bvSBAkEAxHyceppScAQOHHyJ6rOQVMhw78F5B201uPBgi8oYsmiC+gXZIfBsgPKJZVED30WnkwkVHGP3ddoqV6jo3ViUJQ=="
        ];
        return $jsonPath;
    }

    public function createUser($memberId , $nickname , $cardId , $cardName , $certId , $mobile){
        $payment = new \AdaPaySdk\Member();
        $payment->create([
            'app_id' => $this->appid,
            'member_id' => $memberId,
            'nickname' => $nickname,
        ]);
        if ($payment->isError()){
            if ($payment->result['error_code'] == 'member_id_exists'){
                list($status , $msg) = $this->addSettleAccount($memberId , $cardId , $cardName , $certId , $mobile);
                if ($status){
                    return [true , $msg];
                }
                return [false , $msg];
            }
            self::addLogs('createUser' , $payment->result , 'sync_hf');
            return [false , $payment->result['error_msg']];
        }else{
            self::addLogs('createUser' , $payment->result , 'sync_hf');
            $result = $payment->result;
            if ($result['status'] == 'succeeded'){
                // 成功
                list($status , $msg) = $this->addSettleAccount($memberId , $cardId , $cardName , $certId , $mobile);
                if ($status){
                    return [true , $msg];
                }
                return [false , $msg];
            }
        }
        return [false , '未知错误'];
    }

    public function updateUser($memberId , $settleId , $cardId , $cardName , $certId , $mobile , $nickname = ''){
        $payment = new \AdaPaySdk\Member();
        $payment->update([
            'app_id' => $this->appid,
            'member_id' => $memberId ,
            'nickname' => $nickname ,
        ]);
        if ($payment->isError()){
            self::addLogs('updateUser' , $payment->result , 'sync_hf');
            return [false , $payment->result['error_msg']];
        }else{
            self::addLogs('updateUser' , $payment->result , 'sync_hf');
            $result = $payment->result;
            if ($result['status'] == 'succeeded'){
                // 成功
                list($status , $msg) = $this->deleteSettleAccount($memberId , $settleId);
                if ($status){
                    list($status , $msg) = $this->addSettleAccount($memberId , $cardId , $cardName , $certId , $mobile);
                    if ($status){
                        return [true , $msg];
                    }
                }
                return [false , $msg];
            }
        }
        return [false , '未知错误'];
    }


    public function verifySign($data){
        $adapay_tools = new \AdaPaySdk\AdapayTools();

        $sign_flag = $adapay_tools->verifySign($data['data'], $data['sign']);



        if ($sign_flag){
             return true;
        }else{
            return false;
        }
    }


    /**
     * 添加结算账户
     * @param $memberId
     * @param $cardId
     * @param $cardName
     * @param $certId
     * @param $mobile
     * @return array
     * @author <amcolin@126.com>
     * @time 2023/5/29 21:59
     */
    public function addSettleAccount($memberId , $cardId , $cardName , $certId , $mobile){
        $payment = new \AdaPaySdk\SettleAccount();
        $payment->create([
            'app_id' => $this->appid,
            'member_id' => $memberId ,
            'channel'=> 'bank_account',
            'account_info'=> [
                'card_id' => $cardId, //Y 银行卡号
                'card_name' => $cardName, //Y 银行卡对应的户名
                'cert_id' => $certId, //N 证件号，银行账户类型为对私时，必填
                'cert_type' => '00', //N 证件类型，仅支持：00-身份证，银行账户类型为对私时，必填
                'tel_no' => $mobile,//Y 手机号
//                'bank_code' => '03060000', //N 银行编码，详见附录 银行代码，银行账户类型对公时，必填
//                'bank_name' => '建hua', //N 开户银行名称
                'bank_acct_type' => 2, //Y 银行账户类型：1-对公；2-对私
//                'prov_code' => '0031', //N 银行账户开户银行所在省份编码 （省市编码），银行账户类型为对公时，必填
//                'area_code' => '3100',//N 银行账户开户银行所在地区编码（省市编码），银行账户类型为对公时，必填
            ]
        ]);
        if ($payment->isError()){
            self::addLogs('addSettleAccount' , $payment->result , 'sync_hf');
            return [false , $payment->result['error_msg']];
        } else{
            self::addLogs('addSettleAccount' , $payment->result , 'sync_hf');
            return [true , $payment->result['id']];
        }
    }

    /**
     * 删除结算账户
     * @param $memberId
     * @param $settleAccountId
     * @return array
     * @author <amcolin@126.com>
     * @time 2023/5/29 21:59
     */
    public function deleteSettleAccount($memberId , $settleAccountId){
        $payment = new \AdaPaySdk\SettleAccount();
        $account_params = array(
            'app_id'=> $this->appid,
            'member_id'=> $memberId,
            'settle_account_id'=> $settleAccountId
        );
        # 查询结算账户
        $payment->delete($account_params);
        if ($payment->isError()){
            self::addLogs('deleteSettleAccount' , $payment->result , 'sync_hf');
            // array(5) { ["status"]=> string(6) "failed" ["error_type"]=> string(21) "invalid_request_error" ["error_code"]=> string(18) "account_not_exists" ["error_msg"]=> string(21) "结算账户不存在" ["prod_mode"]=> string(4) "true" }
            if ($payment->result['error_code'] == 'account_not_exists'){
                return [true , ''];
            }
            return [false , $payment->result['error_msg']];
        }else{
            self::addLogs('deleteSettleAccount' , $payment->result , 'sync_hf');
            // array(3) { ["id"]=> string(16) "0483226062825344" ["status"]=> string(9) "succeeded" ["prod_mode"]=> string(4) "true" }
            return [true , ''];
        }
    }

    public function selectOrder($paymentId = ''){
        $payment = new \AdaPaySdk\Payment();
        # 请求参数
        $payment_params = array(
            'app_id'=> $this->appid,
            "payment_id"=> $paymentId,
        );
        $payment->queryList($payment_params);
        if ($payment->isError()){
            //失败处理
            self::addLogs('selectOrder' , $payment->result , 'sync_hf');
            return [false , $payment->result['error_msg']];
        } else {
            self::addLogs('selectOrder' , $payment->result , 'sync_hf');
            //成功处理
            if (isset($payment->result['payments'])){
                $payments = $payment->result['payments'][0];
                if ($payments['status'] == 'succeeded'){
                    return [true , $payments['id']];
                }
            }
        }
        return [false , $payment->result];
    }


    public function createOrder($data){
        # 初始化支付确认对象类
        $payment = new \AdaPaySdk\Payment();
        $orderId = $data['order_no'];
        # 支付设置



        $payment_params = array(
            'app_id'=> $this->appid,
            'pay_channel'=> 'wx_lite',
            'order_no'=> $orderId, // 请求订单号，只能为英文、数字或者下划线的一种或多种组合，保证在app_id下唯一
            'pay_amt'=> bcadd($data['pay_amt'], 0,2), // 
            'goods_title' => $data['desc'], // 
            'goods_desc' => $data['desc'] , // 
            'device_info' => ['device_ip'=> $data['ip']],
            'notify_url' => $data['notify_url'],
            // 'fee_mode' => 'O',
            'expend'=> [
                'open_id'=> $data['open_id'],
               
            ]
        );

        if (isset($data['div_members'])) {
           $payment_params['div_members'] = $data['div_members'];
        }



       
        # 创建支付确认对象
        $payment->create($payment_params);
        # 对支付结果进行处理
        if ($payment->isError()){
            self::addLogs('sharing' , $payment->result , 'sync_hf');
            //失败处理
            return [false , $payment->result['error_msg']];
        } else {
            self::addLogs('sharing' , $payment->result , 'sync_hf');
            //成功处理
            if ($payment->result['status'] == 'succeeded'){
                return [true , $payment->result];
            }
        }
        return [false , '未知错误'];
    }
    
    
    public function createOrder2($data){
        # 初始化支付确认对象类
        $payment = new \AdaPaySdk\Payment();
        $orderId = $data['order_no'];
        # 支付设置



        $payment_params = array(
            'app_id'=> $this->appid,
            'pay_channel'=> 'wx_lite',
            'order_no'=> $orderId, // 请求订单号，只能为英文、数字或者下划线的一种或多种组合，保证在app_id下唯一
            'pay_amt'=> bcadd($data['pay_amt'], 0,2), // 
            'goods_title' => $data['desc'], // 
            'goods_desc' => $data['desc'] , // 
            'device_info' => ['device_ip'=> $data['ip']],
            'notify_url' => $data['notify_url'],
            'pay_mode' => 'delay',
            // 'fee_mode' => 'O',
            'expend'=> [
                'open_id'=> $data['open_id'],
               
            ]
        );

        // if (isset($data['div_members'])) {
        //   $payment_params['div_members'] = $data['div_members'];
        // }



        // var_dump($payment_params);
        # 创建支付确认对象
        $payment->create($payment_params);
        # 对支付结果进行处理
        if ($payment->isError()){
            self::addLogs('sharing' , $payment->result , 'sync_hf');
            //失败处理
            return [false , $payment->result['error_msg']];
        } else {
            self::addLogs('sharing' , $payment->result , 'sync_hf');
            //成功处理
            if ($payment->result['status'] == 'succeeded'){
                return [true , $payment->result];
            }
        }
        return [false , '未知错误'];
    }

    public function sharing($paymentId , $confirm_amt , $members = [] , $orderId = ''){
        # 初始化支付确认对象类
        $payment = new \AdaPaySdk\PaymentConfirm();
        $orderId = $orderId ? $orderId : date("YmdHis").rand(100000, 999999);
        # 支付设置
        $payment_params = array(
            'payment_id'=> $paymentId, // Adapay生成的支付对象id
            'order_no'=> $orderId, // 请求订单号，只能为英文、数字或者下划线的一种或多种组合，保证在app_id下唯一
            'confirm_amt'=> bcadd($confirm_amt, 0,2), // 确认金额，必须大于0，保留两位小数点，如0.10、100.05等。必须小于等于原支付金额-已确认金额-已撤销金额。
            'div_members'=> $members , // 分账对象信息列表，一次请求最多仅支持7个分账方。json对象 形式，详见 分账对象信息列表
            'fee_mode' => 'I' , // 手续费收取模式：O-商户手续费账户扣取手续费，I-交易金额中扣取手续费；值为空时，默认值为I；若为O时，分账对象列表中不支持传入手续费承担方
        );
        # 创建支付确认对象
        $payment->create($payment_params);
        # 对支付结果进行处理
        if ($payment->isError()){
            self::addLogs('sharing' , $payment->result , 'sync_hf');
            //失败处理
            return [false , $payment->result['error_msg']];
        } else {
            self::addLogs('sharing' , $payment->result , 'sync_hf');
            //成功处理
            if ($payment->result['status'] == 'succeeded'){
                return [true , $payment->result];
            }
        }
        return [false , '未知错误'];
    }

    public function cancelSharing($payment_confirm_id){
        $request = new \AdaPaySdk\AdaPayCommon();
        $params = [
            'adapay_func_code' => 'payments.confirm.reverse' , // Adapay接口功能号：payments.confirm.reverse
            'payment_confirm_id' => $payment_confirm_id , // Adapay生成的支付确认对象id
            'order_no' => date("YmdHis").rand(100000, 999999) , // 请求订单号，只能为英文、数字或者下划线的一种或多种组合
        ];
        $request->requestAdapay($params);
        if ($request->isError()){
            self::addLogs('cancelSharing' , $request->result , 'sync_hf');
            //失败处理
            return [false , $request->result['error_msg']];
        } else {
            self::addLogs('sharing' , $request->result , 'sync_hf');
            //成功处理
            if ($request->result['status'] == 'succeeded'){
                return [true , $request->result];
            }
        }
        return [false , '未知错误'];
    }

    public function selectBalance($memberId , $settleAccountId){
        $wallet = new \AdaPaySdk\SettleAccount();
        $account_params = array(
            # 应用ID
            'app_id'=> $this->appid,
            # 用户ID
            'member_id'=> $memberId,
            // 由Adapay生成的结算账户对象id，若查询商户本身时，可以为空
            'settle_account_id'=> $settleAccountId
        );
        # 查询账户余额
        $wallet->balance($account_params);
        # 对支付结果进行处理
        if ($wallet->isError()){
            //失败处理
            return [false , $wallet->result['error_msg']];
        } else {
            //成功处理
            if ($wallet->result['status'] == 'succeeded'){
                return [true , [
                    'avl_balance' => $wallet->result['avl_balance'] ,
                    'frz_balance' => $wallet->result['frz_balance'] ,
                    'last_avl_balance' => $wallet->result['last_avl_balance'] ,
                    'acct_balance' => $wallet->result['acct_balance'] ,
                ]];
            }
        }
        return [false , '未知错误'];
    }

    protected static function addLogs($message , $content = [] , $fileName = ''){
        if (is_array($content) && $content){
            $content = ' >> ' . json_encode($content , JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }else{
            $content = '';
        }
        file_put_contents('./'.$fileName.'.log' , '【'.date('Y-m-d H:i:s').'】' . $message . $content . PHP_EOL , FILE_APPEND);
    }




}
